package com.framework.seedkit.utils.encrypt;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class RSAManager {
    
    private static final String TAG = "RSAManager";
    
    private KeyPair mKeyPair;

    /**
     * 描述: 构造函数,主要用于生成公私钥密钥对
     */
    public RSAManager() {
        try {
            mKeyPair = RSA.generateKeyPair();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 描述:用公钥加密,向外部提供的加密API
     * @param originData 原始数据
     * @return 加密后的数据
     */
    public String encrypt(String originData) {
        String ret = null;
        
        try {
            ret = HexUtil.hex(RSA.encryptByPublicKey(originData, mKeyPair.getPublic()));
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        
        return ret;
    }
    
    /**
     * 描述: 用私钥解密,向外部提供的解密API
     * @param encryptedData 待解密数据
     * @return 解密后的数据
     */
    public String decrypt(String encryptedData) {
        byte [] data = HexUtil.unhexba_1(encryptedData);
        String ret = null;
        
        try {
            ret = RSA.decryptByPrivateKey(data, mKeyPair.getPrivate());
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        
        return ret;
    }

    /**
     * 描述: 获取公钥
     */
    public String getPublicKey() {
        String publicKey = RSA.encode(mKeyPair.getPublic().getEncoded());

        return publicKey;
    }

    /**
     * 描述: 获取私钥
     */
    public String getPrivateKey() {
        String privateKey = RSA.encode(mKeyPair.getPrivate().getEncoded());

        return privateKey;
    }
}
